<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>帕累托图</span>
        <el-button
          style="float: right; padding: 3px 0"
          type="text"
          @click="downloadChart">
          下载图表
        </el-button>
      </div>
      <div id="main" style="width: 100%; height: 700px"></div>
    </el-card>
  </div>
</template>

<script>
import axios from "axios";
import * as echarts from "echarts";
import { getToken } from "@/utils/auth";
/* import { WAREHOUSES_PATH } from "../../../api/constants/constants.js"; */

export default {
  name: "FaultChart",
  data() {
    return {
      chart: null
    };
  },
  mounted() {
    this.fetchData();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    async fetchData() {
      try {
        const token = getToken();
        const response = await axios.get(`${process.env.VUE_APP_BASE_API}/wareHouses/NumberOfFailures`, {
         /*  params: {
            excelFilePath: encodeURIComponent(WAREHOUSES_PATH),
          }, */
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });

        if (!response.data || !response.data.source || !Array.isArray(response.data.source)) {
          this.$message.warning('暂无数据');
          return;
        }

        this.initChart(response.data.source);
      } catch (error) {
        console.error("Error fetching data:", error);
        this.$message.error("获取数据失败");
      }
    },
    initChart(data) {
      const chartDom = document.getElementById("main");
      this.chart = echarts.init(chartDom);
      
      // 确保数据按频率降序排序
      const sortedData = data.sort((a, b) => b.Frequency - a.Frequency);
      
      const option = {
        title: {
          text: "故障类别帕累托图",
          left: 'center'
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross"
          },
          formatter: function(params) {
            const barData = params[0];
            const lineData = params[1];
            return `${barData.name}<br/>
                    故障次数：${barData.value}<br/>
                    累计百分比：${lineData.value}%`;
          }
        },
        legend: {
          data: ["故障次数", "累计百分比"],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: "category",
          data: sortedData.map(item => item.FaultCategory),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: [
          {
            type: "value",
            name: "故障次数",
            position: "left"
          },
          {
            type: "value",
            name: "累计百分比",
            position: "right",
            max: 100,
            min: 0,
            axisLabel: {
              formatter: '{value}%'
            }
          }
        ],
        series: [
          {
            name: "故障次数",
            type: "bar",
            data: sortedData.map(item => item.Frequency),
            itemStyle: {
              color: '#409EFF'
            }
          },
          {
            name: "累计百分比",
            type: "line",
            yAxisIndex: 1,
            data: sortedData.map(item => item.CumulativePercentage),
            itemStyle: {
              color: '#67C23A'
            },
            lineStyle: {
              width: 2
            },
            symbol: 'circle',
            symbolSize: 8
          }
        ]
      };

      this.chart.setOption(option);
      
      // 添加窗口大小改变时的自适应
      window.addEventListener('resize', () => {
        this.chart && this.chart.resize();
      });
    },
    downloadChart() {
      if (!this.chart) {
        this.$message.warning('暂无图表数据');
        return;
      }
      
      const now = new Date();
      const fileName = `帕累托图_${now.getFullYear()}${(now.getMonth() + 1).toString().padStart(2, '0')}${now.getDate().toString().padStart(2, '0')}.png`;
      
      try {
        const imgData = this.chart.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        });
        
        const link = document.createElement('a');
        link.href = imgData;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        
        this.$message.success('图表下载成功');
      } catch (error) {
        console.error('下载图表失败:', error);
        this.$message.error('下载图表失败，请重试');
      }
    }
  },
};
</script>

<style scoped>
.box-card {
  margin: 20px;
}
</style>
